package com.cyzy.controller;
import com.cyzy.dto.Result;
import com.cyzy.pojo.Address;
import com.cyzy.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author LIGHT
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    // 新增地址
    @PostMapping("/add")
    public Result addAddress(@RequestBody Address address) {
        Address savedAddress = addressService.addAddressAndReturn(address);
        return savedAddress != null ? 
               Result.ok().message("添加成功").data("address", savedAddress) : 
               Result.error().message("添加失败");
    }

    // 删除地址
    @DeleteMapping("/delete")
    public Result deleteAddress(@RequestParam("id") Long id) {
        boolean deleted = addressService.logicDeleteAddress(id);
        return deleted ? Result.ok().message("删除成功") : Result.error().message("地址不存在或删除失败");
    }

    // 修改地址
    @PutMapping("/update")
    public Result updateAddress(@RequestBody Address address) {
        boolean update = addressService.updateAddress(address);
        return update ? Result.ok().message("修改成功") : Result.error().message("修改失败");
    }

    // 设置默认地址
    @PutMapping("/setDefault")
    public Result setDefaultAddress(@RequestParam("userId") Long userId, @RequestParam("addressId") Long addressId) {
        boolean result = addressService.setDefaultAddress(userId, addressId);
        return result ? Result.ok().message("设置成功") : Result.error().message("设置失败");
    }

    // 查询用户所有地址
    @GetMapping("/list")
    public Result listAddress(@RequestParam("userId") Long userId) {
        List<Address> list = addressService.listValidAddressByUserId(userId);
        return Result.ok().data("list", list);
    }
}
